package com.tongda.menu.activity;

import java.util.ArrayList;
import java.util.List;

import com.tongda.core.common.Constants;
import com.tongda.core.enums.StatusCodeEnum;
import com.tongda.core.repository.MenuDishDao;
import com.tongda.core.service.BaseService;
import com.tongda.core.service.DishService;
import com.tongda.core.service.UserService;
import com.tongda.core.utils.ActivityUtil;
import com.tongda.core.utils.CommunicationUtil;
import com.tongda.core.utils.DishUtil;
import com.tongda.core.utils.ServerIPScanner;
import com.tongda.core.utils.SharedPreferencesUtils;
import com.tongda.core.vo.Dish;
import com.tongda.core.vo.MobileRspResult;
import com.tongda.menu.R;
import com.tongda.menu.util.UpdateVersionHelper;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Html;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.widget.ImageView;
import android.widget.TextView;

public class SplashActivity extends BaseActivity{
	
	protected boolean isServerOk;
	
	private TextView currentProgressTv;
	private ImageView settingImv;
	
		@Override
		protected void onCreate(Bundle savedInstanceState) {
			super.onCreate(savedInstanceState);
			requestWindowFeature(Window.FEATURE_NO_TITLE);
			setContentView(R.layout.activity_splash);
		}
		@Override
		protected void onResume() {
			super.onResume();
			initCurrentView();
		}
		
		@Override
		protected void initCurrentView() {
			TextView versionnameTv = (TextView)findViewById(R.id.versionname);
			versionnameTv.setText("当前版本："+UpdateVersionHelper.getVersionName(this));
			currentProgressTv = (TextView)findViewById(R.id.splash_currentProgress);
			settingImv = (ImageView)findViewById(R.id.splash_settingImv);
			boolean isFirstInstall = (Boolean) SharedPreferencesUtils.getParam(this, "is_first_install", true);
			if(isFirstInstall){
				ActivityUtil.switchActivity(this, false, IntroduceActivity.class);
				overridePendingTransition(R.anim.in_from_right, R.anim.out_to_left);
			}else{
				SharedPreferencesUtils.setParam(SplashActivity.this, "is_first_install", false);
				super.initCurrentView();
			}
		}
		
		@Override
		protected void loadData() {
			Thread isServerOkThread = new Thread(new Runnable() {
				@Override
				public void run() {
					isServerOk  = isServerOk(UserService.getServerIp(SplashActivity.this));
				}
			});
			isServerOkThread.start();
		}
		
		@Override
		protected void describeView() {
			//2.2.0需求不是每次进入都要加载数据的
			if(isUpdateDishes()){
				if(isServerOk){
					new getRests().execute(UserService.getServerIp(SplashActivity.this));
				}else{
					new ScanIpTask().execute();
				}
			}else{
				ActivityUtil.switchActivity(this, true, MainActivity.class);
				Constants.resetServerIp(UserService.getServerIp(SplashActivity.this));
			}
		
			settingImv.setOnClickListener(new View.OnClickListener() {
		
				@Override
				public void onClick(View v) {
					ActivityUtil.switchActivity(SplashActivity.this,false, SettingActivity.class);
					ActivityUtil.Toast(SplashActivity.this, "可以设置", false, false);
				}
			});
		}
	    /*
	     * 更新菜谱的异步任务
	     * */
		public class UpdateDishTask extends AsyncTask<String, Integer, Integer>{
			
			private String TABLE_NAME = "dish";
			private MenuDishDao dish_dao;
			private DishUtil dish_util;
			
			@Override
			protected void onPreExecute() {
				super.onPreExecute();
				dish_dao = MenuDishDao.getInstance(SplashActivity.this);
				dish_util = DishUtil.getInstance(SplashActivity.this);
				currentProgressTv.setText("正在获取服务端数据......");
				settingImv.setClickable(false);
			}
			
			@Override
			protected Integer doInBackground(String... params) {
				List<Dish> dishes = null;
				MobileRspResult rspResult = DishService.synchronizeMenuDishCategary(SplashActivity.this);
				dishes = DishService.synchronizeMenuDish(SplashActivity.this);
				int totalProgress = 0;
				
				if(rspResult.getStatusCode().equals(StatusCodeEnum.SUCCESS.getCode())&&dishes!=null && dishes.size()>0){
					publishProgress(totalProgress);
					totalProgress = dishes.size();
					for(int i=0;i<dishes.size();i++){ 
						Dish dish = dishes.get(i);
						dish_dao.insert(dish,dish_util,TABLE_NAME);
						publishProgress(((i+1)*100)/totalProgress);
					}
				}
			
				return totalProgress;
			}
			
			@Override
			protected void onProgressUpdate(Integer... values) {
				super.onProgressUpdate(values);  
				currentProgressTv.setText("正在初始化菜谱..."+values[0]+"%");
			}
			@Override
			protected void onPostExecute(Integer result) {
				super.onPostExecute(result);
					cancel(true);
					if(result!=0){
						ActivityUtil.switchActivity(SplashActivity.this, true, MainActivity.class);
						overridePendingTransition(R.anim.in_from_right, R.anim.out_to_left);
						ActivityUtil.Toast(SplashActivity.this, "更新了"+result+"道菜!", false, false);
					}else{
						setUpdateDishes(true);
						currentProgressTv.setText("获取数据失败,请检查网络并重新进入菜谱!");
						settingImv.setClickable(true);
					}
			}	
			
		}
		
	    /*
	     * 扫描服务器的异步任务
	     * */
		private class ScanIpTask extends AsyncTask<Void, Void, Void> {
			ArrayList<String> list = null;
			public ProgressDialog progressDialog;
			protected String scanedAvailableServerIp;

			@Override
			protected Void doInBackground(Void... params) {
				ServerIPScanner ip = new ServerIPScanner();
				list = ip.getLanIPList();
				return null;
			}

			@Override
			protected void onPreExecute() {
				progressDialog = new ProgressDialog(SplashActivity.this);
				progressDialog.setTitle("正在扫描可用的服务器");
				progressDialog.setMessage("请您耐心等待...");
				progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
				progressDialog.setCancelable(false);
				progressDialog.show();
				
			}

			@Override
			protected void onPostExecute(Void result) {
				try {
					progressDialog.dismiss();
				} catch (Exception e) {
					e.printStackTrace();
				}
				if (list != null && list.size() == 1) {
					afterChooseIp(list.get(0));
				} else if (list != null && list.size() > 1) {
					scanedAvailableServerIp = list.get(0);
					new AlertDialog.Builder(SplashActivity.this).setTitle("请选择登录服务器IP").setSingleChoiceItems(list.toArray(new String[] {}), 0, new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							 scanedAvailableServerIp = list.get(which);
						}
					}).setPositiveButton("确定", new android.content.DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
							afterChooseIp(scanedAvailableServerIp);
						}
					}).setNegativeButton("刷新", new OnClickListener(){

						@Override
						public void onClick(DialogInterface dialog, int which) {
							cancel(true);
							new ScanIpTask().execute();
						}
						
					}).setCancelable(true).show();
				} else {
						View view = View.inflate(SplashActivity.this, R.layout.servicenotfound, null);
						new AlertDialog.Builder(SplashActivity.this).setTitle(Html.fromHtml("<font color= 'red' type='bold'>"+"未检测到局域网内可用的服务器"+"</font>")).setView(view).setPositiveButton("刷新", new OnClickListener(
								) {
							
							@Override
							public void onClick(DialogInterface dialog, int which) {
								cancel(true);
								new ScanIpTask().execute();
							}
						}).show();
						settingImv.setClickable(true);
				}
			}

			@Override
			protected void onProgressUpdate(Void... values) {
				super.onProgressUpdate(values);
			}

		}
		
		
		void afterChooseIp(String scanedAvailableServerIp) {
			new getRests().execute(scanedAvailableServerIp);
			ActivityUtil.Toast(this, "您使用了：" + scanedAvailableServerIp + "服务器", false, false);
		}
		
	    /*
	     * 快速判断当前默认服务器是否可用
	     * */
		public static boolean isServerOk(String ip) {
			synchronized (Constants.objectLock) {
				String res = CommunicationUtil.get("http://" + ip + ":" + Constants.SERVER_PORT + Constants.SERVER_CONTEXT_PATH + "/mobile/index/isServerOk");
				if (res!=null && "canyin-mobileserver".equals(res)) {
					return true;
				}
				return false;
			}
		}
		
	    @Override
	    public boolean onKeyDown(int keyCode, KeyEvent event) {
	    	if(keyCode==KeyEvent.KEYCODE_BACK){
	    		SplashActivity.this.finish();
	    	}
	    	return super.onKeyDown(keyCode, event);
	    }
	    
	    /*
	     * 拿到所有符合ip地址服务器的餐厅的id的异步任务
	     * */
	    public class getRests extends AsyncTask<String, Void, String>{
	    	
	    	@Override
	    	protected void onPreExecute() {
	    		super.onPreExecute();
	    		setUpdateDishes(false);
	    	}

			@Override
			protected String doInBackground(String... params) {
				Constants.resetServerIp(params[0]);
				SharedPreferencesUtils.setParam(SplashActivity.this, "server_ip", params[0]);
				BaseService.COOKIE_STR = "username=" + "super" + ";password=" + "mixi8canyin";
				
				//对餐厅的ID进行赋值
//				Employee employee = UserService.getCurrentUserByLoginUsername("super");
//				Constants.RESTAURANT_ID = employee.getRestaurantId();
//				SharedPreferencesUtils.setParam(SplashActivity.this, "rstId", Constants.RESTAURANT_ID);
				return null;
			}
	    	
			@Override
			protected void onPostExecute(String result) {
				super.onPostExecute(result);
				new UpdateDishTask().execute();
				cancel(true);
			}
			
	    }

}
